package org.cuit.lmq.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.cuit.lmq.constants.enums.BodyStatusEnum;
import org.cuit.lmq.domain.common.BaseContextHolder;
import org.cuit.lmq.domain.common.Result;
import org.cuit.lmq.domain.po.BodyInfo;
import org.cuit.lmq.exception.CustomException;
import org.cuit.lmq.service.BodyInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Seon
 * @since 2023-03-03
 */
@RestController
@RequestMapping("/user")
public class BodyInfoController {

    @Autowired
    private BodyInfoService bodyInfoService;

    @PostMapping("/body/addInfo")
    public Result<?> addBodyInfo(@RequestBody BodyInfo bodyInfo) {
        double bmi = bodyInfo.getWeight() / Math.pow(bodyInfo.getHeight() / 100, 2);
        bodyInfo.setBmi(bmi);
        bodyInfo.setUserId(BaseContextHolder.getCurrentUserId());
        BodyStatusEnum bodyStatus = bodyInfoService.judgeBodyStatus(bodyInfo);
        bodyInfo.setBodyStatus(bodyStatus);
        try {
            bodyInfoService.save(bodyInfo);
            return Result.success(true);
        } catch (CustomException ce) {
            ce.printStackTrace();
            return Result.fail("添加失败", 0);
        }
    }

    @GetMapping("/body/getAllData")
    public Result<?> getAllBodyData() {
        LambdaQueryWrapper<BodyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BodyInfo::getUserId, BaseContextHolder.getCurrentUserId());
        wrapper.orderByDesc(BodyInfo::getCreateTime);
        List<BodyInfo> list = bodyInfoService.list(wrapper);
        if (!list.isEmpty()) {
            return Result.success(list);
        } else {
            return Result.success("暂无身体数据信息");
        }
    }

    @DeleteMapping("/body/delInfo")
    public Result<?> delBodyInfo(@RequestBody Map<String, String> parameters) {
        String bodyInfoId = parameters.get("bodyInfoId");
        if (StringUtils.isBlank(bodyInfoId)) {
            return Result.fail("id为空，请重试", 0);
        }
        LambdaQueryWrapper<BodyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BodyInfo::getUserId, BaseContextHolder.getCurrentUserId());
        wrapper.eq(BodyInfo::getId, bodyInfoId);
        boolean remove = bodyInfoService.remove(wrapper);
        if (remove) {
            return Result.success(true);
        } else {
            return Result.fail("不能删除非本人的身体数据", 0);
        }
    }

}

